package cn.ztuo.bitrade.service;

import cn.ztuo.bitrade.dao.AnswerTopicDao;
import cn.ztuo.bitrade.entity.AnswerTopic;
import cn.ztuo.bitrade.entity.QAnswerTopic;
import cn.ztuo.bitrade.service.Base.BaseService;
import cn.ztuo.bitrade.util.PredicateUtils;
import cn.ztuo.bitrade.vo.AnswerTopicVO;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: Xiazt
 * @date: 2020-04-22 11:50
 */
@Service
public class AnswerTopicService extends BaseService {

    @Autowired
    private AnswerTopicDao answerTopicDao;

    public List<AnswerTopic> findAll() {
        return answerTopicDao.findAll();
    }

    public Page<AnswerTopic> getByPage(AnswerTopicVO answerTopicVO) {
        ArrayList<BooleanExpression> booleanExpressions = new ArrayList<>();

        // 查询条件
        if (StringUtils.isNotEmpty(answerTopicVO.getTopic())) {
            booleanExpressions.add(QAnswerTopic.answerTopic.topic.like("%" + answerTopicVO.getTopic() + "%"));
        }

        Predicate predicate = PredicateUtils.getPredicate(booleanExpressions);
        // 排序条件
        Sort sort = new Sort(Sort.Direction.ASC, "sortNumber");
        Pageable pageable = new PageRequest(answerTopicVO.getPageNum() - 1, answerTopicVO.getPageSize(), sort);

        return answerTopicDao.findAll(predicate, pageable);
    }

    public AnswerTopic insert(AnswerTopic answerTopic) {
        return answerTopicDao.save(answerTopic);
    }

    @Transactional
    public void delete(Long id){
         answerTopicDao.delete(id);
    }

    public AnswerTopic findById(Long id){
        return answerTopicDao.findById(id);
    }


}
